package com.tree.treeoj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.tree.treeoj.annotation.AuthCheck;
import com.tree.treeoj.common.BaseResponse;
import com.tree.treeoj.common.DeleteRequest;
import com.tree.treeoj.common.ErrorCode;
import com.tree.treeoj.common.ResultUtils;
import com.tree.treeoj.constant.UserConstant;
import com.tree.treeoj.exception.BusinessException;
import com.tree.treeoj.exception.ThrowUtils;
import com.tree.treeoj.model.dto.question.QuestionRelationQueryRequest;
import com.tree.treeoj.model.dto.questionbank.QuestionBankAddRequest;
import com.tree.treeoj.model.dto.questionbank.QuestionBankEditRequest;
import com.tree.treeoj.model.dto.questionbank.QuestionBankQueryRequest;
import com.tree.treeoj.model.dto.questionbank.QuestionBankUpdateRequest;
import com.tree.treeoj.model.entity.QuestionBank;
import com.tree.treeoj.model.entity.QuestionRelation;
import com.tree.treeoj.model.entity.User;
import com.tree.treeoj.model.vo.QuestionBankVO;
import com.tree.treeoj.model.vo.QuestionRelationVO;
import com.tree.treeoj.service.QuestionBankService;
import com.tree.treeoj.service.QuestionRelationService;
import com.tree.treeoj.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题库接口
 *
 */
@RestController
@RequestMapping("/question_bank")
@Slf4j
public class QuestionBankController {

    @Resource
    private QuestionBankService questionBankService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param questionBankAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestionBank(@RequestBody QuestionBankAddRequest questionBankAddRequest, HttpServletRequest request) {
        if (questionBankAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankAddRequest, questionBank);
        List<String> tags = questionBankAddRequest.getTags();
        if (tags != null) {
            questionBank.setTags(GSON.toJson(tags));
        }
        questionBankService.validQuestionBank(questionBank, true);
        User loginUser = getLoginUser(request);
        questionBank.setUserId(loginUser.getId());
        questionBank.setFavourNum(0);
        questionBank.setThumbNum(0);
        boolean result = questionBankService.save(questionBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionBankId = questionBank.getId();
        return ResultUtils.success(newQuestionBankId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionBank(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionBank.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionBankService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionBankUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionBank(@RequestBody QuestionBankUpdateRequest questionBankUpdateRequest) {
        if (questionBankUpdateRequest == null || questionBankUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankUpdateRequest, questionBank);
        List<String> tags = questionBankUpdateRequest.getTags();
        if (tags != null) {
            questionBank.setTags(GSON.toJson(tags));
        }
        // 参数校验
        questionBankService.validQuestionBank(questionBank, false);
        long id = questionBankUpdateRequest.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionBankService.updateById(questionBank);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据 id 获取题库")
    public BaseResponse<QuestionBankVO> getQuestionBankVoById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = questionBankService.getById(id);
        if (questionBank == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionBankService.getQuestionBankVo(questionBank, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionBankVO>> listQuestionBankVoByPage(@RequestBody QuestionBankQueryRequest questionBankQueryRequest,
            HttpServletRequest request) {
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size),
                questionBankService.getQueryWrapper(questionBankQueryRequest));
        return ResultUtils.success(questionBankService.getQuestionBankVoPage(questionBankPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionBankVO>> listMyQuestionBankVoByPage(@RequestBody QuestionBankQueryRequest questionBankQueryRequest,
            HttpServletRequest request) {
        if (questionBankQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = getLoginUser(request);
        questionBankQueryRequest.setUserId(loginUser.getId());
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size),
                questionBankService.getQueryWrapper(questionBankQueryRequest));
        return ResultUtils.success(questionBankService.getQuestionBankVoPage(questionBankPage, request));
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param questionBankEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestionBank(@RequestBody QuestionBankEditRequest questionBankEditRequest, HttpServletRequest request) {
        if (questionBankEditRequest == null || questionBankEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankEditRequest, questionBank);
        List<String> tags = questionBankEditRequest.getTags();
        if (tags != null) {
            questionBank.setTags(GSON.toJson(tags));
        }
        // 参数校验
        questionBankService.validQuestionBank(questionBank, false);
        User loginUser = getLoginUser(request);
        long id = questionBankEditRequest.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestionBank.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionBankService.updateById(questionBank);
        return ResultUtils.success(result);
    }
    @Resource
    QuestionRelationService questionRelationService;
    /**
     * 分页获取题库列表（仅管理员）
     *
     * @param questionRelationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "分页获取题库列表（仅管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionRelation>> listQuestionRelationByPage(@RequestBody QuestionRelationQueryRequest questionRelationQueryRequest,
                                                                           HttpServletRequest request) {
        long current = questionRelationQueryRequest.getCurrent();
        long size = questionRelationQueryRequest.getPageSize();
        QueryWrapper<QuestionRelation> questionRelationQueryWrapper = questionRelationService.getQueryWrapper(questionRelationQueryRequest);
        Page<QuestionRelation> questionRelationPage = questionRelationService.page(new Page<>(current, size),questionRelationQueryWrapper);
        return ResultUtils.success(questionRelationPage);
    }

    /**
     * 根据题库id分页获取题目列表
     *
     * @param questionRelationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/question/vo")
    @ApiOperation(value = "根据 题库id 获取题目")
    public BaseResponse<Page<QuestionRelationVO>> listQuestionRelationVoByPage(@RequestBody QuestionRelationQueryRequest questionRelationQueryRequest, HttpServletRequest request) {
        long questionBankId = questionRelationQueryRequest.getQuestionBankId();
        long current = questionRelationQueryRequest.getCurrent();
        long size = questionRelationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        if (questionBankId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        if (questionBank == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
//        QueryWrapper<QuestionRelation> questionRelationQueryWrapper = questionRelationService.getQueryWrapper(questionRelationQueryRequest);
//        List<QuestionRelation> questionRelationList = questionRelationService.list(questionRelationQueryWrapper);
//
//        List<Question> questionList = questionRelationList.stream().map(questionRelation -> questionService.getById(questionRelation.getQuestionId())).collect(Collectors.toList());
//        List<QuestionVO> questionVOList = questionList.stream().map(question -> questionService.getQuestionVO(question,loginUser)).collect(Collectors.toList());

        Page<QuestionRelation> questionRelationPage = questionRelationService.page(new Page<>(current, size),questionRelationService.getQueryWrapper(questionRelationQueryRequest));
        Page<QuestionRelationVO> questionRelationVOPage = questionRelationService.getQuestionRelationVOPage(questionRelationPage,loginUser);

        return ResultUtils.success(questionRelationVOPage);
    }

    private User getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return loginUser;
    }
}
